import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

// 导入组件(同时设置路由懒加载)
// 一级路由
const login = () => import ('@/views/login/index.vue');
const layout = () => import ('@/layout/index.vue');
const search = () => import ('@/views/search/index.vue');
const chat = () => import ('@/views/chat/index.vue');
// 二级路由
const home = () => import ('@/views/home/index.vue');
const ask = () => import ('@/views/ask/index.vue');
const video = () => import ('@/views/video/index.vue');
const mine = () => import ('@/views/mine/index.vue');
const edit = () => import ('@/views/mine/edit/index.vue');
const particulars = () => import ('@/views/home/particulars/index.vue');
const routes = [{
    path: '/login',
    name: 'login',
    component: login
  },
  {
    path: '',
    redirect: '/login'
  },
  {
    name: 'chat',
    path: '/mine/chat',
    component: chat,
    // 添加路由元信息
    meta: {
      allowable: true
    }
  },
  {
    name: 'edit',
    path: '/mine/edit',
    component: edit
  },
  {
    name: 'particulars',
    path: '/particulars',
    component: particulars
  },
  {
    name: 'search',
    path: '/search',
    component: search,
    meta: {
      needKing: true
    }
  },
  {
    path: '/layout',
    component: layout,
    redirect: '/layout/home',
    children: [{
        name: 'home',
        path: 'home',
        component: home,
        meta: {
          needKing: true
        }
      },
      {
        name: 'ask',
        path: 'ask',
        component: ask
      },
      {
        name: 'video',
        path: 'video',
        component: video
      },
      {
        name: 'mine',
        path: 'mine',
        component: mine,
        // 添加路由元信息
        meta: {
          allowable: true
        }
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 导入store
import {
  store
} from '@/store/index.js';

// 设置全局前置的路由守卫
// 在即将进入某个路由前调用
// 前置守卫有三个参数 to from next
// to 到哪去；from 从哪来；next 是一个函数，调用next函数代表放行(允许访问该路由)
router.beforeEach((to, from, next) => {
  // 判断去的是不是需要验证token的页面
  if (to.meta.allowable) {
    // 进到这里说明需要进行登录验证,判断有没有携带token
    if (store.state.tokenObj.token) {
      // 有token就放行
      next()
    } else {
      // 设置轻提示
      Vue.prototype.$toast.fail('请先登录')
      // 将用户挡回登录页,并且携带参数(原本要访问的页面)
      next('/login?back=' + to.path)
    }
  } else {
    // 进到这里说明不需要登录验证，直接放行
    next()
  }
})

// 用于消除vue-router3.1版本之后的路由跳转出错时的报错
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(to) {
  return VueRouterPush.call(this, to).catch(err => err)
}

export default router